<template>
  <div class="function-child">
    <je-panel v-bind="childrenFieldOptions" ref="childPanel">
      <template #default>
        <je-table
          ref="xTable"
          border
          stripe
          auto-resize
          sync-resize
          show-overflow="ellipsis"
          keep-source
          show-header-overflow
          resizable
          draggable
          header-align="center"
          height="100%"
          :scroll-y="{ mode: 'wheel' }"
          :edit-config="{
            trigger: 'click',
            mode: 'cell',
            showUpdateStatus: true,
          }"
          :row-config="{ isCurrent: true, isHover: true }"
          :loading="loading"
          :store="tableData"
          size="mini"
          id-property="JE_CORE_FUNCRELATION_ID"
          @checkbox-change="selectionChange"
          @checkbox-all="selectionChange"
          @drop="formFieldItemDrop"
        >
          <template #tbar>
            <div class="top">
              <je-button type="text" @click="clickChildImport">
                <i class="fal fa-file-import"></i> 导入
              </je-button>
              <!-- <je-button type="text" @click="clickChildAdd">
                <i class="fal fa-plus-circle"></i> 添加
              </je-button> -->
              <je-button type="text" @click="showModal({ type: 'addChild' })">
                <i class="jeicon jeicon-plus-circle"></i> 自定义</je-button
              >
              <je-button type="text" @click="handleUpdate">
                <i class="fal fa-save"></i> 保存</je-button
              >
              <je-button type="text" @click="handleDelete">
                <i class="fal fa-times"></i> 删除</je-button
              >
              <!-- <je-button type="text"> <i class="fal fa-cogs"></i> 查看功能配置</je-button> -->

              <div class="searchWrap">
                <je-input-search
                  v-model:value.trim="searchValue"
                  class="search"
                  placeholder="搜索"
                  allow-clear
                  enter-button="搜索"
                  style="width: 240px"
                  @search="getData"
                >
                  <template #prefix> <i class="fal fa-search" /> </template>
                </je-input-search>
              </div>
            </div>
          </template>
          <je-table-column align="center" type="checkbox" width="40"></je-table-column>
          <je-table-column field="SY_ORDERINDEX" title="序号" align="center" width="60">
          </je-table-column>
          <je-table-column field="FUNCRELATION_NAME" title="名称" min-width="140" :edit-render="{}">
            <template #default="{ row }">
              <span v-html="formatHightText(searchValue, row.FUNCRELATION_NAME)"></span>
            </template>
            <template #edit="{ row }"> <je-input v-model:value="row.FUNCRELATION_NAME" /></template>
            <!-- <template #edit="{ row }">
              <GridSelect
                v-model:value="row.FUNCRELATION_NAME"
                editable
                config-info="JE_CORE_FUNCINFO,FUNCRELATION_NAME~FUNCRELATION_CODE~FUNCRELATION_TABLENAME,FUNCINFO_FUNCNAME~FUNCINFO_FUNCCODE~FUNCINFO_TABLENAME,S"
                :querys="[
                  {
                    code: 'SY_JESYS',
                    type: '=',
                    value: '1',
                  },
                ]"
              />
            </template> -->
          </je-table-column>
          <je-table-column
            field="FUNCRELATION_CODE"
            title="编码"
            width="220"
            :edit-render="{ autofocus: '.ant-input' }"
          >
            <template #default="{ row }">
              <span v-html="formatHightText(searchValue, row.FUNCRELATION_CODE)"></span>
            </template>
            <template #edit="{ row }">
              <je-input
                v-if="row.FUNCRELATION_RELYONTYPE == 'file'"
                v-model:value.trim="row.FUNCRELATION_CODE"
              />
              <span
                v-if="row.FUNCRELATION_RELYONTYPE == 'func'"
                style="padding-left: 10px"
                v-html="formatHightText(searchValue, row.FUNCRELATION_CODE)"
              ></span>
            </template>
          </je-table-column>

          <je-table-column align="center" width="80" title="授权">
            <template #default="{ row }">
              <div class="iconWrap" style="cursor: pointer" @click="handlePerm(row)">
                <i class="jeicon jeicon-seal"></i>
              </div>
            </template>
          </je-table-column>

          <je-table-column align="center" field="FUNCRELATION_RELYONTYPE" title="类型" width="140">
            <template #default="{ row }">
              {{
                getSelectCodeToLabel('JE_FUNC_CHILD_TYPE', row.FUNCRELATION_RELYONTYPE)
              }}</template
            >
          </je-table-column>

          <je-table-column
            field="FUNCRELATION_TABLENAME"
            width="250"
            :edit-render="{ autofocus: '.ant-input' }"
          >
            <template #header>
              <div>
                <i
                  class="fas fa-question-circle"
                  style="color: #c0c4cc"
                  :style="changeColor(tableTipShow)"
                  @click="
                    clickTipView(FUNCRELATION_TABLENAME_UNITPLE, '表名|配置项|附件字段编码说明')
                  "
                  @mouseenter="tableTipShow = true"
                  @mouseleave="tableTipShow = false"
                />
                表名|配置项|附件字段编码
              </div>
            </template>
            <template #edit="{ row }">
              <je-input v-model:value.trim="row.FUNCRELATION_TABLENAME" />
            </template>
          </je-table-column>

          <je-table-column
            align="center"
            field="FUNCRELATION_SHOWTYPE"
            title="展示方式"
            width="200"
            :edit-render="{}"
          >
            <template #edit="{ row }">
              <je-select
                v-model:value="row.FUNCRELATION_SHOWTYPE"
                allow-clear
                config-info="JE_FUNC_CHILD_LAYOUT,row.FUNCRELATION_SHOWTYPE,code,S"
                :querys="[
                  {
                    code: 'DICTIONARYITEM_ITEMCODE',
                    type: 'notIn',
                    value: ['formInnerGroup'],
                  },
                ]"
              />
            </template>
            <template #default="{ row }">{{
              getSelectCodeToLabel('JE_FUNC_CHILD_LAYOUT', row.FUNCRELATION_SHOWTYPE)
            }}</template>
          </je-table-column>
          <je-table-column
            v-if="originType == 'app'"
            field="FUNCRELATION_USE_SCOPE"
            title="适用范围"
            align="center"
            width="120"
            :edit-render="{}"
          >
            <template #edit="{ row }">
              <je-select v-model:value="row.FUNCRELATION_USE_SCOPE">
                <je-select-option
                  v-for="(item, index) in getScopedList"
                  :key="index"
                  :value="item.code"
                  :style="`color: ${item.textColor}`"
                >
                  {{ item.text }}</je-select-option
                >
              </je-select>
            </template>
            <template #default="{ row }"
              ><div :style="`color: ${getColor('JE_META_USE_SCOPE', row.FUNCRELATION_USE_SCOPE)}`">
                {{ getSelectCodeToLabel('JE_META_USE_SCOPE', row.FUNCRELATION_USE_SCOPE) }}
              </div></template
            >
          </je-table-column>
          <je-table-column
            v-if="originType == 'app'"
            align="center"
            min-width="140"
            title="移动端配置"
          >
            <template #default="{ row }">
              <je-dropdown :trigger="['click']">
                <span style="cursor: pointer"
                  >手机配置 <i style="margin-left: 6px" class="fal fa-angle-down"></i
                ></span>
                <template #overlay>
                  <je-menu style="width: 460px">
                    <je-app-config :func-config="getRowConfig(row)"></je-app-config>
                  </je-menu>
                </template>
              </je-dropdown>
            </template>
          </je-table-column>
          <je-table-column
            field="FUNCRELATION_INTERPRETER"
            title="显隐表达式"
            width="360"
            :edit-render="{ autofocus: '.ant-input' }"
          >
            <template #edit="{ row }">
              <je-input v-model:value.trim="row.FUNCRELATION_INTERPRETER">
                <template #suffix>
                  <i
                    class="setIcon fal fa-cog"
                    @click="
                      showExpress(
                        {
                          key: 'FUNCRELATION_INTERPRETER',
                          value: row.FUNCRELATION_INTERPRETER,
                        },
                        row,
                      )
                    "
                  ></i>
                </template>
              </je-input>
            </template>
          </je-table-column>
          <je-table-column
            align="center"
            field="FUNCRELATION_ZCGX"
            title="主从关系"
            width="200"
            :edit-render="{}"
          >
            <template #header>
              <div>
                <i
                  class="fas fa-question-circle"
                  style="color: #c0c4cc"
                  :style="changeColor(unitTipShow)"
                  @click="clickTipView(FUNCRELATION_ZCGX_UNITPLE, '主从关系说明')"
                  @mouseenter="unitTipShow = true"
                  @mouseleave="unitTipShow = false"
                />
                主从关系
              </div>
            </template>
            <template #edit="{ row }">
              <je-select
                v-if="row.FUNCRELATION_RELYONTYPE == 'func'"
                v-model:value="row.FUNCRELATION_ZCGX"
                :options="MASTER_SALAVE_RELATION"
              />
              <div v-else> {{ getSelectLabel(row.FUNCRELATION_ZCGX, MASTER_SALAVE_RELATION) }}</div>
            </template>
            <template #default="{ row }">{{
              getSelectLabel(row.FUNCRELATION_ZCGX, MASTER_SALAVE_RELATION)
            }}</template>
          </je-table-column>

          <je-table-column
            align="center"
            field="FUNCRELATION_ENABLED"
            title="启用"
            width="130"
            type="switch"
          />

          <!-- <je-table-column
            align="center"
            field="FUNCRELATION_COPY"
            title="级联复制"
            width="130"
            type="switch"
          /> -->

          <!-- <je-table-column
            align="center"
            field="FUNCRELATION_SHOWTITLE"
            title="显示标题"
            width="130"
            type="switch"
          /> -->

          <je-table-column
            align="center"
            field="FUNCRELATION_LOCATE"
            title="表单定位"
            width="130"
            type="switch"
          />

          <je-table-column
            field="FUNCRELATION_GROUP"
            title="分组"
            width="140"
            :edit-render="{ autofocus: '.ant-input' }"
          >
            <template #header>
              <div>
                <i
                  class="fas fa-question-circle"
                  style="color: #c0c4cc"
                  :style="changeColor(groupTipShow)"
                  @click="clickTipView(FUNCRELATION_CHILD_FIELD_UNITPLE, '分组说明', 800)"
                  @mouseenter="groupTipShow = true"
                  @mouseleave="groupTipShow = false"
                />
                分组
              </div>
            </template>
            <template #edit="{ row }">
              <je-input v-model:value.trim="row.FUNCRELATION_GROUP" />
            </template>
          </je-table-column>

          <je-table-column
            field="FUNCRELATION_HEIGHT"
            title="高度"
            width="140"
            :edit-render="{ autofocus: '.ant-input' }"
          >
            <template #edit="{ row }">
              <je-input-number
                v-model:value="row.FUNCRELATION_HEIGHT"
                :min="0"
                :parser="(value) => value.replace(/[^0-9]+/g, '')"
                style="width: 100%"
              />
            </template>
          </je-table-column>

          <je-table-column
            field="FUNCRELATION_ICON"
            title="标题图标"
            width="140"
            :edit-render="{ autofocus: '.ant-input' }"
          >
            <template #edit="{ row }">
              <div class="inputWrap">
                <je-icon v-model:value="row.FUNCRELATION_ICON"></je-icon>
              </div>
            </template>
          </je-table-column>

          <!-- <je-table-column
            field="FUNCRELATION_ENTITYNAME"
            title="JS控制器"
            width="140"
            :edit-render="{ autofocus: '.ant-input' }"
          >
            <template #header>
              <div> JS控制器 <i class="fas fa-flower" style="color: rgb(235, 235, 235)"></i> </div>
            </template>
            <template #edit="{ row }">
              <je-input v-model:value.trim="row.FUNCRELATION_ENTITYNAME" />
            </template>
          </je-table-column> -->
        </je-table>
      </template>
      <template #bottom>
        <div class="table">
          <je-table
            ref="xTable2"
            border
            stripe
            auto-resize
            sync-resize
            show-overflow="ellipsis"
            keep-source
            show-header-overflow
            resizable
            header-align="center"
            :edit-config="{
              trigger: 'click',
              mode: 'cell',
              showStatus: true,
            }"
            :loading="loading1"
            :row-config="{ isCurrent: true, isHover: true }"
            :store="tableData2"
            size="mini"
            id-property="JE_CORE_ASSOCIATIONFIELD_ID"
            @checkbox-change="selectionChange2"
            @checkbox-all="selectionChange2"
          >
            <template #tbar>
              <div class="top">
                <je-button type="text" @click="handleSave2">
                  <i class="fal fa-plus-circle"></i> 添加
                </je-button>
                <je-button type="text" @click="handleUpdate2">
                  <i class="fal fa-save"></i> 保存</je-button
                >
                <je-button type="text" @click="handleDelete2">
                  <i class="fal fa-times"></i> 删除</je-button
                >

                <div class="searchWrap">
                  <je-input-search
                    v-model:value.trim="searchValue2"
                    class="search"
                    placeholder="搜索"
                    allow-clear
                    enter-button="搜索"
                    style="width: 240px"
                    @search="getData2"
                  >
                    <template #prefix> <i class="fal fa-search" /> </template>
                  </je-input-search>
                </div>
              </div>
            </template>

            <je-table-column align="center" type="checkbox" width="40"></je-table-column>
            <je-table-column
              field="ASSOCIATIONFIELD_PRIFIELDNAME"
              title="字段名称"
              width="140"
              :edit-render="{}"
            >
              <template #default="{ row }">
                <span
                  v-html="formatHightText(searchValue2, row.ASSOCIATIONFIELD_PRIFIELDNAME)"
                ></span>
              </template>
              <template #edit="{ row }">
                <GridSelect
                  v-model:value="row.ASSOCIATIONFIELD_PRIFIELDNAME"
                  config-info="JE_CORE_RESOURCECOLUMN,ASSOCIATIONFIELD_PRIFIELDNAME~ASSOCIATIONFIELD_PRIFIELDCODE,RESOURCECOLUMN_NAME~RESOURCECOLUMN_CODE,S"
                  :querys="[
                    {
                      code: 'RESOURCECOLUMN_FUNCINFO_ID',
                      type: '=',
                      value: row.ASSOCIATIONFIELD_FID,
                      cn: 'and',
                    },
                  ]"
                />
              </template>
            </je-table-column>
            <je-table-column field="ASSOCIATIONFIELD_PRIFIELDCODE" title="字段编码" width="220">
              <template #default="{ row }">
                <span
                  v-html="formatHightText(searchValue2, row.ASSOCIATIONFIELD_PRIFIELDCODE)"
                ></span>
              </template>
              <!-- <template #edit="{ row }">
                    <je-input v-model:value.trim="row.ASSOCIATIONFIELD_PRIFIELDCODE" />
                  </template> -->
            </je-table-column>
            <je-table-column
              field="ASSOCIATIONFIELD_CHIFIELDNAME"
              title="(子功能)字段名称"
              width="160"
              :edit-render="{ autofocus: '.ant-input' }"
            >
              <template #default="{ row }">
                <span
                  v-html="formatHightText(searchValue2, row.ASSOCIATIONFIELD_CHIFIELDNAME)"
                ></span>
              </template>
              <template #edit="{ row }">
                <GridSelect
                  v-model:value="row.ASSOCIATIONFIELD_CHIFIELDNAME"
                  config-info="JE_CORE_RESOURCECOLUMN,ASSOCIATIONFIELD_CHIFIELDNAME~ASSOCIATIONFIELD_CHIFIELDCODE,RESOURCECOLUMN_NAME~RESOURCECOLUMN_CODE,S"
                  :editable="true"
                  :querys="[
                    {
                      code: 'RESOURCECOLUMN_FUNCINFO_ID',
                      type: '=',
                      value: row.ASSOCIATIONFIELD_PID,
                      cn: 'and',
                    },
                  ]"
                />
              </template>
            </je-table-column>
            <je-table-column
              field="ASSOCIATIONFIELD_CHIFIELDCODE"
              title="(子功能)字段编码"
              width="220"
              :edit-render="{ autofocus: '.ant-input' }"
            >
              <template #default="{ row }">
                <span
                  v-html="formatHightText(searchValue2, row.ASSOCIATIONFIELD_CHIFIELDCODE)"
                ></span>
              </template>
              <template #edit="{ row }">
                <je-input v-model:value.trim="row.ASSOCIATIONFIELD_CHIFIELDCODE" />
              </template>
            </je-table-column>
            <je-table-column
              align="center"
              field="ASSOCIATIONFIELD_TRANSMIT"
              title="传值"
              width="130"
              type="switch"
            />
            <je-table-column
              align="center"
              field="ASSOCIATIONFIELD_WHERECON"
              title="where条件"
              width="130"
              type="switch"
            />
            <je-table-column
              align="center"
              field="ASSOCIATIONFIELD_ASSOCIATION"
              title="关联关系"
              width="140"
              :edit-render="{}"
            >
              <template #edit="{ row }">
                <je-select
                  v-model:value="row.ASSOCIATIONFIELD_ASSOCIATION"
                  allow-clear
                  config-info="JE_FUNC_CHILD_ASSOCIATION,row.ASSOCIATIONFIELD_ASSOCIATION,code,S"
                />
              </template>
              <template #default="{ row }">{{
                getSelectCodeToLabel('JE_FUNC_CHILD_ASSOCIATION', row.ASSOCIATIONFIELD_ASSOCIATION)
              }}</template>
            </je-table-column>
            <je-table-column
              field="ASSOCIATIONFIELD_SQL"
              title="自定义sql"
              min-width="340"
              :edit-render="{ autofocus: '.ant-input' }"
            >
              <template #edit="{ row }">
                <je-input v-model:value="row.ASSOCIATIONFIELD_SQL">
                  <template #suffix>
                    <i class="setIcon fal fa-cog" @click="showSql('ASSOCIATIONFIELD_SQL', row)"></i>
                  </template>
                </je-input>
              </template>
            </je-table-column>
            <!-- <je-table-column
              align="center"
              field="ASSOCIATIONFIELD_CASCADEUPDATE"
              title="级联更新(一对一表单时起效)"
              width="220"
              type="switch"
            />
            <je-table-column
              align="center"
              width="220"
              field="ASSOCIATIONFIELD_DELCHILD"
              title="级联删除(非主外键关系起效)"
              type="switch"
            /> -->
          </je-table>
        </div>
      </template>
    </je-panel>
    <div v-if="modalOption.modalFlag">
      <component
        :is="modalOption.activeModal"
        :visble="modalOption.modalFlag"
        :record-data="recordData"
        @changeModal="changeModal"
      ></component>
    </div>
  </div>
</template>

<script>
  import {
    ref,
    toRefs,
    reactive,
    defineComponent,
    onMounted,
    watch,
    onBeforeMount,
    nextTick,
  } from 'vue';
  import {
    Modal,
    Grid,
    Icon,
    Panel,
    Button,
    Menu,
    Input,
    InputNumber,
    Checkbox,
    Select,
    InputSelect,
    Data,
    Dropdown,
  } from '@jecloud/ui';
  import { formatHightText } from '@/helper/common.js';
  import { FUNCTION_CHILD_COMPONENTS } from '@/helper/function-child-components';

  import {
    ChildFuncGetData,
    ChildFuncImportData,
    ChildFuncUpdate,
    ChildFuncRemove,
    ChildFuncFieldSave,
    ChildFuncFieldUpdate,
    ChildFuncFieldRemove,
    ChildFuncPerm,
  } from '@/api/index';

  import { SelectWindow } from '@jecloud/func';

  import { ListenerExpressModal } from '@/helper/index.js';

  import { showFuncQuerys } from '@jecloud/func';

  import { useFuncStore } from '@/store/func-store';

  import { AddChildModal } from './components/add-child';

  import {
    FUNCRELATION_TABLENAME_UNITPLE,
    FUNCRELATION_CHILD_FIELD_UNITPLE,
    FUNCRELATION_ZCGX_UNITPLE,
  } from '@/helper/tip-constant.jsx';

  import { getDDItemInfo, isNotEmpty, loadDDItemByCodes, getDDItemList } from '@jecloud/utils';

  import JeAppConfig from '@/views/config/components/app-config.vue';

  export default defineComponent({
    name: 'FunctionChild',
    components: {
      JeButton: Button,
      JeInput: Input,
      JeInputNumber: InputNumber,
      JeInputSearch: Input.Search,
      JeCheckbox: Checkbox,
      JeTable: Grid,
      JeAppConfig,
      JeTableColumn: Grid.Column,
      JeDropdown: Dropdown,
      JeSelect: Select,
      JeSelectOption: Select.Option,
      JeIcon: Icon,
      JePanel: Panel,
      JeMenu: Menu,
      GridSelect: InputSelect.Grid,
      TreeSelect: InputSelect.Tree,
      ...FUNCTION_CHILD_COMPONENTS,
    },
    props: {
      recordData: {
        type: Object,
        default: () => {},
      },
      origin: String,
    },
    setup(props) {
      const state = reactive({
        getScopedList: [],
        funcData: props.recordData,
        originType: props.origin,
        xTable: ref(),
        xTable2: ref(),
        searchValue: '',
        searchValue2: '',
        tableData: Data.Store.useGridStore({
          data: [],
        }),
        tableData2: Data.Store.useGridStore({
          data: [],
        }),
        isAllowClick: false, // 授权按钮防重复提交
        selectTableData: [],
        selectTableData2: [],
        unitTipShow: false,
        groupTipShow: false,
        tableTipShow: false,
        loading: true,
        loading1: false,
        funcId: props.recordData.JE_CORE_FUNCINFO_ID,
        childPanel: ref(),
        childrenFieldOptions: {
          bottom: { split: true, size: 400 },
        },
        formatHightText,
        FUNCRELATION_TABLENAME_UNITPLE,
        FUNCRELATION_CHILD_FIELD_UNITPLE,
        FUNCRELATION_ZCGX_UNITPLE,
        MASTER_SALAVE_RELATION: [
          { value: '1:1', label: '一对一' },
          { value: '1:n', label: '一对多' },
        ],
      });

      // 这边做的一个处理就是当选择两个及其以上的时候，下面的关联关系的数据是要清空的
      watch(
        () => state.selectTableData,
        (val) => {
          if (val.length > 1 || val.length == 0) {
            state.tableData2.loadData([]);
          }
        },
        { deep: true },
      );
      const modalOption = reactive({
        modalFlag: false, // 默认modal都是隐藏的false
        activeModal: '', // 默认没有激活的弹窗类型
      });
      const methods = {
        // 获取手机配置对应row的功能信息
        getRowConfig(row) {
          return {
            funcId: row.FUNCRELATION_FUNCID,
            funcCode: row.FUNCRELATION_CODE,
            funcType: 'FUNC',
          };
        },
        //value转label
        getSelectLabel(value, list, valueProp = 'value', labelField = 'label') {
          const item = list.find((item) => item[valueProp] === value);
          return item ? item[labelField] : null;
        },
        // 点击表名|配置项｜附件字段编码的文字说明
        clickTipView(content, title, width) {
          Modal.alert({
            content,
            title,
            icon: 'fal fa-info-circle',
            status: 'info',
            width: width || 640,
          });
        },
        // 改变tip浮上去的颜色
        changeColor(flag) {
          if (flag) {
            return 'cursor:pointer;color: #3265F5';
          }
          return 'cursor:pointer;';
        },
        // 点击自定义sql
        showSql(key, row) {
          showFuncQuerys({
            value: row.ASSOCIATIONFIELD_SQL,
            funcId: state.selectTableData[0].FUNCRELATION_FUNCID,
            callback: (val) => {
              row[key] = val;
            },
          });
        },
        // 显隐藏表达式
        showExpress(obj, row) {
          obj.funcId = state.funcId;
          ListenerExpressModal({
            ...obj,
            callback: (res) => {
              row[obj.key] = res.value;
            },
          });
        },
        // 导入子功能
        clickChildImport() {
          SelectWindow.show({
            title: '选择子功能',
            type: 'grid',
            configInfo: 'JE_CORE_FUNCINFO,,,M',
            querys: [
              {
                type: '=',
                code: 'SY_JESYS',
                value: '1',
              },
              {
                code: 'FUNCINFO_NODEINFOTYPE',
                type: '=',
                value: 'FUNC',
              },
              {
                type: 'and',
                value: [
                  {
                    type: '=',
                    code: 'SY_PARENT',
                    value: state.funcId,
                  },

                  {
                    type: 'notInSelect',
                    code: 'JE_CORE_FUNCINFO_ID',
                    value: {
                      table: 'JE_CORE_FUNCRELATION',
                      code: 'FUNCRELATION_FUNCID',
                      conditions: [
                        {
                          code: 'FUNCRELATION_FUNCINFO_ID',
                          type: '=',
                          value: state.funcId,
                        },
                        {
                          code: 'FUNCRELATION_FUNCID',
                          type: 'notNull',
                        },
                      ],
                    },
                  },
                ],
              },
            ],
            callback: function ({ rows }) {
              let arr = rows.map((item) => item.JE_CORE_FUNCINFO_ID);

              const childParams = {
                ids: arr.join(','),
                FUNCRELATION_FUNCINFO_ID: state.funcId,
              };

              ChildFuncImportData(childParams)
                .then((res) => {
                  res.data.forEach((item) => {
                    state.tableData.insert(item.values);
                  });
                  Modal.message(res.message, 'success');
                })
                .catch((error) => {
                  Modal.alert(error.message, 'error');
                });
            },
          });
        },
        // 添加子功能
        clickChildAdd() {
          SelectWindow.show({
            title: '选择子功能',
            type: 'grid',
            configInfo: 'JE_CORE_FUNCINFO,,,M',
            orders: [{ code: 'SY_CREATETIME', type: 'DESC' }],
            querys: [
              {
                code: 'FUNCINFO_FUNCTYPE',
                type: 'in',
                value: ['FUNC', 'FUNCFIELD'],
                cn: 'and',
              },
              {
                type: 'and',
                value: [
                  {
                    type: 'notInSelect',
                    code: 'JE_CORE_FUNCINFO_ID',
                    value: {
                      table: 'JE_CORE_FUNCRELATION',
                      code: 'FUNCRELATION_FUNCID',
                      conditions: [
                        {
                          code: 'FUNCRELATION_FUNCINFO_ID',
                          type: '=',
                          value: state.funcId,
                        },
                        {
                          code: 'FUNCRELATION_FUNCID',
                          type: 'notNull',
                        },
                      ],
                    },
                  },
                ],
              },
            ],
            callback: function ({ rows }) {
              let arr = rows.map((item) => item.JE_CORE_FUNCINFO_ID);

              const childParams = {
                ids: arr.join(','),
                FUNCRELATION_FUNCINFO_ID: state.funcId,
              };
              ChildFuncImportData(childParams)
                .then((res) => {
                  res.data.forEach((item) => {
                    state.tableData.insert(item.values);
                  });
                  Modal.message('添加成功', 'success');
                })
                .catch((error) => {
                  Modal.alert(error.message, 'error');
                });
            },
          });
        },
        // 拖拽排序
        formFieldItemDrop() {
          state.tableData.data.forEach((item, index) => {
            item.SY_ORDERINDEX = index + 1;
          });
        },
        showModal() {
          // modalOption.modalFlag = true;
          // modalOption.activeModal = obj.type;
          AddChildModal({
            title: '添加子功能',
            recordData: props.recordData,
            callback: (res) => {
              res.isRefresh && methods.getData();
            },
          });
        },

        changeModal(obj) {
          modalOption.modalFlag = obj.visible;
          obj.isRefresh && methods.getData();
        },

        // 选择 table
        selectionChange(obj) {
          state.selectTableData = obj.records;

          if (state.selectTableData.length !== 0) {
            methods.getData2();
          }
        },

        // 选择 table2
        selectionChange2(obj) {
          state.selectTableData2 = obj.records;
        },
        getColor(dictionary, code) {
          const item = getDDItemInfo(dictionary, code);
          if (isNotEmpty(item)) {
            return item.textColor;
          }
          return '';
        },
        getSelectCodeToLabel(dictionary, code) {
          const item = getDDItemInfo(dictionary, code);

          if (isNotEmpty(item)) {
            return item.text;
          }
          return '';
        },

        handlePerm(row) {
          if (state.isAllowClick) {
            return false;
          }
          state.isAllowClick = true;
          const funcStore = useFuncStore();
          const params = {
            subFuncId: row.JE_CORE_FUNCRELATION_ID,
            productId: funcStore.product.id,
          };
          ChildFuncPerm(params)
            .then((res) => {
              state.isAllowClick = false;
              Modal.message(res.message, 'success');
            })
            .catch((error) => {
              state.isAllowClick = false;
              Modal.alert(error.message, 'error');
            });
        },

        getData() {
          state.loading = true;
          const params = {
            tableCode: 'JE_CORE_FUNCRELATION',
            funcId: state.funcId,
            j_query: JSON.stringify({
              custom: [
                { code: 'FUNCRELATION_FUNCINFO_ID', value: state.funcId, type: '=', cn: 'and' },
                {
                  type: 'and',
                  value: [
                    { type: 'like', code: 'FUNCRELATION_CODE', value: state.searchValue },
                    { type: 'like', code: 'FUNCRELATION_NAME', value: state.searchValue, cn: 'or' },
                  ],
                },
              ],
              order: [{ code: 'SY_ORDERINDEX', type: 'ASC' }],
            }),
          };
          ChildFuncGetData(params)
            .then((res) => {
              const data = res.rows || [];
              state.tableData.loadData(data);
              state.loading = false;
            })
            .catch((error) => {
              Modal.alert(error.message, 'error');
            });
        },

        getData2() {
          if (state.selectTableData.length === 0 || state.selectTableData.length > 1) {
            state.tableData2.loadData([]);
            return false;
          }
          state.loading1 = true;
          const params = {
            tableCode: 'JE_CORE_ASSOCIATIONFIELD',
            j_query: '',
            funcId: state.funcId,
          };

          const j_query = {
            custom: [],
            order: [{ code: 'SY_ORDERINDEX', type: 'ASC' }],
          };

          if (state.searchValue2) {
            j_query.custom = [
              {
                code: 'ASSOCIATIONFIELD_FUNCRELAT_ID',
                value: state.selectTableData[0].JE_CORE_FUNCRELATION_ID,
                type: '=',
                cn: 'and',
              },
              {
                type: 'and',
                value: [
                  {
                    type: 'like',
                    code: 'ASSOCIATIONFIELD_CHIFIELDCODE',
                    value: state.searchValue2,
                    cn: 'or',
                  },
                  {
                    type: 'like',
                    code: 'ASSOCIATIONFIELD_CHIFIELDNAME',
                    value: state.searchValue2,
                    cn: 'or',
                  },
                  {
                    type: 'like',
                    code: 'ASSOCIATIONFIELD_PRIFIELDCODE',
                    value: state.searchValue2,
                    cn: 'or',
                  },
                  {
                    type: 'like',
                    code: 'ASSOCIATIONFIELD_PRIFIELDNAME',
                    value: state.searchValue2,
                    cn: 'or',
                  },
                ],
              },
            ];
          } else {
            j_query.custom = [
              {
                code: 'ASSOCIATIONFIELD_FUNCRELAT_ID',
                value: state.selectTableData[0].JE_CORE_FUNCRELATION_ID,
                type: '=',
                cn: 'and',
              },
            ];
          }

          params.j_query = JSON.stringify(j_query);

          ChildFuncGetData(params)
            .then((res) => {
              state.tableData2.loadData(res.rows);
              state.loading1 = false;
            })
            .catch((error) => {
              Modal.alert(error.message, 'error');
            });
        },

        handleSave2() {
          if (state.selectTableData.length === 0) {
            Modal.alert('请选择子功能信息，再进行关联字段添加...', 'info');
            return false;
          }
          // 这边添加一个逻辑
          // 如果state.selectTableData.length的长度>1时候，要注意底部的数据为空；
          if (state.selectTableData.length > 1) {
            state.tableData2.loadData([]);
            Modal.alert('请选择一个子功能信息进行关联字段', 'info');
            return false;
          }
          const params = {
            tableCode: 'JE_CORE_ASSOCIATIONFIELD',
            ASSOCIATIONFIELD_FUNCRELAT_ID: state.selectTableData[0].JE_CORE_FUNCRELATION_ID,
            ASSOCIATIONFIELD_PID: state.selectTableData[0].FUNCRELATION_FUNCID,
            ASSOCIATIONFIELD_FID: state.selectTableData[0].FUNCRELATION_FUNCINFO_ID,
          };

          ChildFuncFieldSave(params, {})
            .then(async (res) => {
              const { data } = res;
              state.tableData2.insert(data);
            })
            .catch((error) => {
              Modal.alert(error.message, 'error');
            });
        },

        handleUpdate() {
          const updateRecords = state.tableData.getChanges();
          if (updateRecords.length === 0) {
            Modal.message('无数据操作!', 'info');
            return false;
          }
          const data = [];
          const changeData = [];
          updateRecords.forEach((item) => {
            data.push(item._record);
            const changeItem = {
              JE_CORE_FUNCRELATION_ID: item._record.JE_CORE_FUNCRELATION_ID,
            };
            Object.keys(item).forEach((key) => {
              if (key != '_record') {
                changeItem[key] = item[key].newValue || '';
              }
            });
            changeData.push(changeItem);
          });
          const params = {
            tableCode: 'JE_CORE_FUNCRELATION',
            funcId: state.funcId,
            strData: JSON.stringify(changeData),
          };

          ChildFuncUpdate(params)
            .then((res) => {
              Modal.message(res.message, 'success');

              methods.getData();
            })
            .catch((error) => {
              Modal.alert(error.message, 'error');
            });
        },

        handleUpdate2() {
          const updateRecords = state.tableData2.getChanges();
          if (updateRecords.length === 0) {
            Modal.message('无数据操作!', 'info');
            return false;
          }
          const data = [];
          const changeData = [];
          updateRecords.forEach((item) => {
            data.push(item._record);
            const changeItem = {
              JE_CORE_ASSOCIATIONFIELD_ID: item._record.JE_CORE_ASSOCIATIONFIELD_ID,
            };
            Object.keys(item).forEach((key) => {
              if (key != '_record') {
                changeItem[key] = item[key].newValue || '';
              }
            });
            changeData.push(changeItem);
          });
          const params = {
            tableCode: 'JE_CORE_ASSOCIATIONFIELD',
            funcId: state.funcId,
            strData: JSON.stringify(changeData),
          };

          ChildFuncFieldUpdate(params)
            .then((res) => {
              Modal.message(res.message, 'success');
              data.forEach((item) => {
                state.tableData2.commitRecord(item);
              });
            })
            .catch((error) => {
              Modal.alert(error.message, 'error');
            });
        },

        handleDelete() {
          if (state.selectTableData.length === 0) {
            Modal.alert('请选择要删除的数据！', 'warning');
            return false;
          }

          Modal.confirm('确定删除选中的数据吗？', () => {
            methods.doDelete();
          });
        },

        doDelete() {
          const ids = state.selectTableData.map((item) => item.JE_CORE_FUNCRELATION_ID).join(',');

          const params = {
            tableCode: 'JE_CORE_FUNCRELATION',
            ids,
          };
          ChildFuncRemove(params)
            .then((res) => {
              Modal.message(res.message, 'success');
              state.selectTableData.forEach((item) => {
                state.tableData.remove(item);
              });
              state.selectTableData = [];
              state.tableData2.loadData([]);
              // methods.getData();
            })
            .catch((error) => {
              Modal.alert(error.message, 'error');
            });
        },

        handleDelete2() {
          if (state.selectTableData2.length === 0) {
            Modal.alert('请选择要删除的数据！', 'warning');
            return false;
          }

          Modal.confirm('确定删除选中的数据吗？', () => {
            methods.doDelete2();
          });
        },

        doDelete2() {
          const ids = state.selectTableData2
            .map((item) => item.JE_CORE_ASSOCIATIONFIELD_ID)
            .join(',');

          const params = {
            tableCode: 'JE_CORE_ASSOCIATIONFIELD',
            ids,
          };
          ChildFuncFieldRemove(params)
            .then((res) => {
              Modal.message(res.message, 'success');
              state.selectTableData2.forEach((item) => {
                state.tableData2.remove(item);
              });
              state.selectTableData2 = [];
              // methods.getData2();
            })
            .catch((error) => {
              Modal.alert(error.message, 'error');
            });
        },
      };

      onBeforeMount(() => {
        // 获取字典数据
        loadDDItemByCodes([
          'JE_FUNC_CHILD_TYPE',
          'JE_FUNC_CHILD_LAYOUT',
          'JE_FUNC_CHILD_ASSOCIATION',
          'JE_META_USE_SCOPE',
        ]);
        state.getScopedList = getDDItemList('JE_META_USE_SCOPE') || [
          { code: 'ALL', text: '全部', textColor: '', icon: 'fal fa-phone-laptop' },
          { code: 'APP', text: '移动端', textColor: '#02A863', icon: 'fal fa-mobile-phone' },
          { code: 'PC', text: '电脑端', textColor: '#3265F5', icon: 'fal fa-laptop' },
        ];
      });

      onMounted(() => {
        nextTick(() => {
          methods.getData();
        });
      });

      return {
        ...toRefs(state),
        ...methods,
        modalOption,
      };
    },
  });
</script>

<style lang="less">
  .function-child {
    .searchWrap {
      margin: 0 0 0 auto;
      .ant-input-search {
        border-bottom-right-radius: 0;
        border-top-right-radius: 0;
      }
      .ant-input-affix-wrapper-focused {
        box-shadow: none !important;
      }
      .ant-btn {
        width: 60px;
        background: #3265f5;
      }
    }
  }
</style>

<style lang="less" scoped>
  .function-child {
    height: 100%;
    .top {
      display: flex;
      align-items: center;
      height: 40px;
      padding: 0 20px 0 4px;
      background: #f7f9fc;
      > .ant-btn {
        padding: 4px 12px !important;
        &:hover {
          color: #3f3f3f !important;
          background: #d9d9d9 !important;
        }
      }
    }
    .table {
      height: 100%;
      .iconWrap {
        cursor: pointer;
      }
    }
    .inputWrap {
      position: relative;
      .setIcon {
        position: absolute;
        top: 50%;
        right: 15px;
        transform: translate(0, -50%);
        cursor: pointer;
        z-index: 10000;
      }
    }
  }
</style>
